function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { Alert, Divider } from 'antd';
import React, { useContext, useEffect, useLayoutEffect, useMemo, useRef } from 'react';
import { DsContext } from "../base/common";
import { Layout, useRefState, useUpdateEffect, util } from "../util";
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
var numberStyle = {
  fontWeight: 600,
  color: '#000'
};
var supportType = {
  avg: ['平均'],
  max: ['最大'],
  min: ['最小'],
  sum: ['总'],
  totalSummary: ['总', 'sum']
};
var defaultState = {
  selectedRows: [],
  selectedRowKeys: [],
  aggregateColumns: []
};

/**
 * 表格顶部的警告提示，展现需要汇总的数据
 */
export var TableAlert = /*#__PURE__*/React.memo(function (_ref) {
  var table = _ref.table;
  var pageCahce = useRef({
    state: defaultState
  });
  var _table$state$params = table.state.params,
    pageIndex = _table$state$params.pageIndex,
    pageSize = _table$state$params.pageSize;
  var _useRefState = useRefState(defaultState),
    _useRefState2 = _slicedToArray(_useRefState, 2),
    state = _useRefState2[0],
    setState = _useRefState2[1];
  var ds = useContext(DsContext);
  var checkDataIndex = table.getCheckBoxDataIndex();
  useMemo(function () {
    pageCahce.current.state = state;
  }, [pageIndex, pageSize]);
  var newState = useMemo(function () {
    var innerState = {
      selectedRows: _toConsumableArray(pageCahce.current.state.selectedRows),
      selectedRowKeys: _toConsumableArray(pageCahce.current.state.selectedRowKeys),
      aggregateColumns: []
    };
    table.getAggregateData().forEach(function (r) {
      var keyV = r[table.getKeyField()];
      var startIndex = pageCahce.current.state.selectedRowKeys.indexOf(keyV);
      if (startIndex > -1) {
        r[checkDataIndex] = true;
        // 清除当前页的缓存记录，保证选中行状态切换的准确性
        pageCahce.current.state.selectedRowKeys.splice(startIndex, 1);
        pageCahce.current.state.selectedRows.splice(startIndex, 1);
      } else if (r[checkDataIndex]) {
        innerState.selectedRows.push(r);
        innerState.selectedRowKeys.push(keyV);
      }
    });
    table.alertObj.state = innerState;
    return innerState;
  }, [ds, checkDataIndex]);
  useEffect(function () {
    var _table$generateColumn = table.generateColumns(),
      normalColumns = _table$generateColumn.normalColumns,
      fixedColumns = _table$generateColumn.fixedColumns;
    var allColumns = [].concat(_toConsumableArray(normalColumns), _toConsumableArray(fixedColumns.left.columns), _toConsumableArray(fixedColumns.right.columns));
    allColumns.forEach(function (c) {
      if (!c.hidden && c.dataIndex && c.aggregates) {
        var supportAggregates = c.aggregates.filter(function (a) {
          return supportType.hasOwnProperty(a.type || a);
        });
        if (supportAggregates.length) {
          newState.aggregateColumns.push({
            dataIndex: c.dataIndex,
            aggregates: supportAggregates.map(function (ag) {
              return {
                label: getAgName(c, ag, table),
                type: supportType[ag.type || ag][1] || ag.type || ag,
                encrypted: c.encrypted,
                formatter: function formatter(value, options) {
                  return util.isFunction(ag.formatter) ? ag.formatter(value, options) : value;
                }
              };
            })
          });
        }
      }
    });
    setState(newState);
  }, [newState]);
  useEffect(function () {
    table.alertObj.state = state;
  }, [state]);
  useUpdateEffect(function () {
    pageCahce.current.state.selectedRowKeys.length && table.refreshView({});
  }, [pageCahce.current.state]);
  useEffect(function () {
    return table.subscribe(function () {
      table.alertObj.state = defaultState;
      pageCahce.current.state = defaultState;
      setState(defaultState);
    }, 'clearCacheCheckState');
  }, []);
  var isMessageRender = state.selectedRowKeys.length > (table.settingContainer ? 0 : 1);
  var messageRender = function messageRender() {
    if (isMessageRender) {
      var tableAlertRender = util.isFunction(table.props.tableAlertRender) ? table.props.tableAlertRender : function (_ref2) {
        var selectedRowKeys = _ref2.selectedRowKeys,
          selectedRows = _ref2.selectedRows,
          onClear = _ref2.onClear;
        return /*#__PURE__*/_jsxs("div", {
          style: {
            display: 'flex',
            alignItems: 'center',
            gap: 20,
            fontSize: 12
          },
          children: [/*#__PURE__*/_jsxs("div", {
            children: ["\u5DF2\u9009 ", /*#__PURE__*/_jsx("span", {
              style: numberStyle,
              children: selectedRowKeys.length
            }), " \u9879", /*#__PURE__*/_jsx("a", {
              onClick: onClear,
              style: {
                marginInlineStart: 8
              },
              children: "\u53D6\u6D88\u9009\u62E9"
            })]
          }), state.aggregateColumns.map(function (c) {
            return /*#__PURE__*/_jsx("div", {
              children: c.aggregates.map(function (_ref3, index) {
                var label = _ref3.label,
                  type = _ref3.type,
                  formatter = _ref3.formatter,
                  encrypted = _ref3.encrypted;
                return /*#__PURE__*/_jsxs(React.Fragment, {
                  children: [index > 0 && /*#__PURE__*/_jsx(Divider, {
                    type: "vertical"
                  }), label, /*#__PURE__*/_jsx("span", {
                    style: numberStyle,
                    children: formatter(util.getAggregate(encrypted ? 'encrypted' : type, selectedRows, c.dataIndex), {
                      type: type,
                      dataIndex: c.dataIndex,
                      data: selectedRows
                    })
                  })]
                }, type);
              })
            }, c.dataIndex);
          })]
        });
      };
      return tableAlertRender({
        selectedRowKeys: state.selectedRowKeys,
        selectedRows: state.selectedRows,
        onClear: function onClear() {
          return table.clearSelected();
        }
      });
    }
    return null;
  };
  var render = function render() {
    var layout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    var content = messageRender();
    var message = layout ? /*#__PURE__*/_jsxs(Layout, {
      direction: "row",
      children: [/*#__PURE__*/_jsx(Layout.Flex, {
        children: content
      }), /*#__PURE__*/_jsx(Extra, {
        container: table.settingContainer
      })]
    }) : content;
    return /*#__PURE__*/_jsx(Alert, {
      message: message,
      type: "info",
      showIcon: !!content,
      style: {
        minHeight: 36
      }
    });
  };
  if (table.settingContainer) {
    return render(true);
  }
  if (isMessageRender) {
    return render(false);
  }
  return null;
});
function Extra(_ref4) {
  var container = _ref4.container;
  var innerRef = useRef(null);
  useLayoutEffect(function () {
    if (container && innerRef.current) {
      innerRef.current.appendChild(container);
      return function () {
        var _innerRef$current;
        return (_innerRef$current = innerRef.current) === null || _innerRef$current === void 0 ? void 0 : _innerRef$current.removeChild(container);
      };
    }
  }, []);
  return /*#__PURE__*/_jsx("div", {
    ref: innerRef,
    style: {
      display: 'flex',
      minHeight: 18,
      alignItems: 'center',
      fontSize: 12
    }
  });
}
function getAgName(c, ag, table) {
  var title = util.isFunction(c.header) ? c.header({
    title: c.title,
    dataIndex: c.dataIndex,
    column: c,
    table: table
  }) : c.header || c.title;
  return "".concat(supportType[ag.type || ag][0]).concat(title, ": ");
}